#include <iostream>
#include <memory>
#include <cassert>
#include <malloc.h>
#include "account.h"
#include <unistd.h>
#include "3_3pv.h"
#if 0
Account *create_account(int code, double balance)
{

    Account *a = (Account *)malloc(sizeof(Account));
    assert(a != NULL);
    a->code = code;
    a->balance = balance;
    pthread_mutex_init(&a->mutex, NULL);
}

//销毁账户
void destroy_account(Account *a)
{

    assert(a != NULL);
    pthread_mutex_destroy(&a->mutex);
    free(a);
}
#endif


//取款
double withdraw(Account *a, double amt)
{
    
    assert(a!=NULL);

    P(a->semid,0,1);//零号信号量进行p1操作/信号灯操作 p1操作

    if (amt < 0 || amt > a->balance)
    {
        V(a->semid,0,1);
        return 0.0;
    }
    //取款
    double balance = a->balance; // balance是账户余额 amt是要取多少钱
    sleep(1);
    balance -= amt;
    a->balance = balance;
    
    V(a->semid,0,1);   //这里和互斥锁类似，这两个pv操作之间区域类似于互斥锁之间的临界区

    return amt;
}

//存款
double deposit(Account *a, double amt)
{
    // a不能为空
    assert(a != NULL);
    //代码临界区
    P(a->semid,0,1);
    if (amt < 0)
    {

       V(a->semid,0,1);
        return 0.0;
    }

    double balance = a->balance;

    balance += amt;
   
    return amt;
}

//查看账户余额
double get_balance(Account *a)
{
    P(a->semid,0,1);
    double balance = a->balance;
    std::cout << "账户余额是：" << a->balance << std::endl;
    V(a->semid,0,1);
    return balance;
}
